(function($){


var guid = +new Date,
	container = $("<div style=display:none />"),
	tempElement = document.createElement("div"),
	
	addEvent = document.addEventListener ? 
		function(element, type, handler){ element.addEventListener(type, handler, false); } :
		function(element, type, handler){ element.attachEvent("on" + type, handler); },

	callbackMethodName = function(){
		var methodName;
		while(++guid){
			methodName = "uploadfileCallbackMethod" + guid;
			if(window[methodName] === undefined){
				return methodName;
			}
		}
	};

$.fn.uploadfile = function(options){
	var input = this.eq(0),
		callbackMethod,
		url,
		form,
		iframe,
		replacement,
		callbackField;
	
	options = $.extend(true, {}, options);


	

	//TODO use jQuery.fn.bind to bind event, fire event once like as jQuery.fn.one(firefox), yyy;
	//input.bind("change.uploadfile", function(){
	addEvent(input[0], "change", function(){
		var success;
		
		//abort previous post
		if(callbackMethod){
			window[callbackMethod] = function(){};
		}
		
		//options.success should be a function object or a name of global method
		if($.isFunction(options.success)){
			success = options.success;
		}else if(typeof options.success === "string"){
			success = window[options.success];
		}
		
		//create new callback method
		callbackMethod = callbackMethodName();
		window[callbackMethod] = function(){
			if($.isFunction(options.success)){
				success.apply(input[0], arguments);
			}
			
			iframe.parentNode.removeChild(iframe);
			form.parentNode.removeChild(form);
			iframe = null;
			form = null;
			callbackField = null;
		};
		
		//generate callback field
		callbackField = $("<input type=hidden name=callback />").val(callbackMethod);
		
		//generate iframe
		tempElement.innerHTML = '<iframe name="' + callbackMethod + '" src="javascript:void 0;"></iframe>';
		iframe = tempElement.getElementsByTagName("iframe")[0];
		
		//generate form
		tempElement.innerHTML = '<form method="post" enctype="multipart/form-data" action="' + options.url + '" target="' + iframe.name + '"></form>';
		form = tempElement.getElementsByTagName("form")[0];
		
		//replace input-file with file-cloneNode
		replacement = input[0].cloneNode(false);
		input.replaceWith(replacement);
		
		//add these element to the document
		container.append(iframe);
		container.append(form);
		input.appendTo(form);
		callbackField.appendTo(form);
		if(!container.parent().length){
			container.appendTo("body");
		}
		
		console.log(form.innerHTML)
		form.submit();
		
		//revert input-file
		$(replacement).replaceWith(input);
		
		//TODO focus and blur the input-file, i don't know what happened on ie8.
		input.focus();
		input.blur();
	});
};



})(jQuery);